package com.ys.service.mail.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bo.util.DateUtil;
import com.ys.entity.base.TbFileInfo;
import com.ys.entity.mail.MailDraft;
import com.ys.entity.mail.MailMain;
import com.ys.entity.mail.MailMainTag;
import com.ys.entity.mail.MailReceiver;
import com.ys.entity.mail.MailReceiverDeleted;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.base.TbFileInfoEnum;
import com.ys.enume.mail.MailEnum;
import com.ys.enume.mail.MailReceiverEnum;
import com.ys.mapper.base.TbFileInfoMapper;
import com.ys.mapper.mail.MailDraftMapper;
import com.ys.mapper.mail.MailMainMapper;
import com.ys.mapper.mail.MailMainTagMapper;
import com.ys.mapper.mail.MailMapper;
import com.ys.mapper.mail.MailReceiverDeletedMapper;
import com.ys.mapper.mail.MailReceiverMapper;
import com.ys.service.mail.MailService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;

@Service("mailService")
public class MailServiceImpl implements MailService {
	
	@Autowired
	private MailMapper mailMapper;
	@Autowired
	private MailMainMapper mailMainMapper;
	@Autowired
	private MailMainTagMapper mailMainTagMapper;
	@Autowired
	private MailDraftMapper mailDraftMapper;
	@Autowired
	private MailReceiverMapper mailReceiverMapper;
	@Autowired
	private MailReceiverDeletedMapper mailReceiverDeletedMapper;
	@Autowired
	private TbFileInfoMapper tbFileInfoMapper;

	@Override
	@Transactional
	public R sendMail(Long draftId,
			String title, Integer emergent, String detail,
			String receiverArr,
			String copyerArr,
			String tagArr) {
		
		if (title == null || title.length() == 0) {
			return R.error("标题不能为空");
		}
		
		// 验证收件人
		JSONArray receiverJA = JSON.parseArray(receiverArr);
		if (receiverJA.size() == 0) {
			return R.error("收件人不能为空");
		}
		List<String> listUserId = new ArrayList<String>();
		String receivers = ""; // 收件人拼接，用于存入主表
		for (int i = 0; i < receiverJA.size(); i++) {
			JSONObject receiverJO = receiverJA.getJSONObject(i);
			String userId = receiverJO.getString("userId");
			if (listUserId.contains(userId)) {
				return R.error("收件人【" + userId + "】重复了");
			}
			listUserId.add(userId);
			
			// 拼接收件人
			String userName = receiverJO.getString("userName");
			receivers = receivers + userName + "[" + userId + "],";
		}
		receivers = receivers.length() > 0 ? receivers.substring(0, receivers.length() - 1) : receivers;
		
		// 验证抄送人
		String copyers = ""; // 抄送人拼接，用于存入主表
		JSONArray copyerJA = JSON.parseArray(copyerArr);
		for (int i = 0; i < copyerJA.size(); i++) {
			JSONObject copyerJO = copyerJA.getJSONObject(i);
			String userId = copyerJO.getString("userId");
			if (listUserId.contains(userId)) {
				return R.error("抄送人【" + userId + "】重复了");
			}
			listUserId.add(userId);
			
			// 拼接抄送人
			String userName = copyerJO.getString("userName");
			copyers = copyers + userName + "[" + userId + "],";
		}
		copyers = copyers.length() > 0 ? copyers.substring(0, copyers.length() - 1) : copyers;
		
		// 拼接标签
		String tags = ""; // 标签拼接，用于存入主表
		JSONArray tagJA = JSON.parseArray(tagArr);
		for (int i = 0; i < tagJA.size(); i++) {
			JSONObject tagJO = tagJA.getJSONObject(i);
			
			// 拼接抄送人
			String name = tagJO.getString("name");
			tags = tags + name + ",";
		}
		tags = tags.length() > 0 ? tags.substring(0, tags.length() - 1) : tags;
		
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		
		// 草稿箱附件信息
		List<TbFileInfo> listTbFileInfo = new TbFileInfo()
				.setSourceId(draftId)
				.setSourceCode("ExtraFile")
				.setSourceType(TbFileInfoEnum.SourceType.MAIL_Draft.value)
				.queryList();
		Integer numTbFileInfo = listTbFileInfo != null ? listTbFileInfo.size() : 0;
		
		/*
		 * 添加主邮件
		 */
		MailMain entity = null;
		{
			String extraFile = numTbFileInfo + "个附件";
			Long createChangeId = tsUserChange.getId();
			entity = MailMain.mailMain(title, emergent, detail, extraFile, createChangeId, receivers, copyers, tags, 1);
			mailMainMapper.insert(entity);
		}
		
		/*
		 * 添加附件
		 */
		if (listTbFileInfo != null) {
			for(TbFileInfo tbFileInfo : listTbFileInfo) {
				tbFileInfo
					.setSourceId(entity.getId())
					.setSourceType(TbFileInfoEnum.SourceType.MAIL_Main.value)
					.setSourceCode("ExtraFile");
				tbFileInfoMapper.insert(tbFileInfo);
			}
		}
		
		/*
		 * 添加标签
		 */
		for (int i = 0; i < tagJA.size(); i++) {
			JSONObject tagJO = tagJA.getJSONObject(i);
			Long mainId = entity.getId();
			Long tagId = tagJO.getLong("id");
			MailMainTag mailMainTag = MailMainTag.mailMainTag(mainId, tagId, 1);
			mailMainTagMapper.insert(mailMainTag);
		}
		
		/*
		 * 添加收件人
		 */
		for (int i = 0; i < receiverJA.size(); i++) {
			JSONObject receiverJO = receiverJA.getJSONObject(i);
			Long mainId = entity.getId();
			String userId = receiverJO.getString("userId");
			Integer type = MailReceiverEnum.Type.RECEIVE.value;
			Integer stateRead = MailReceiverEnum.StateRead.NOT.value;
			MailReceiver mailReceiver = MailReceiver.mailReceiver(mainId, userId, type, stateRead, 1);
			mailReceiverMapper.insert(mailReceiver);
		}
		
		/*
		 * 添加抄送人
		 */
		for (int i = 0; i < copyerJA.size(); i++) {
			JSONObject copyerJO = copyerJA.getJSONObject(i);
			Long mainId = entity.getId();
			String userId = copyerJO.getString("userId");
			Integer type = MailReceiverEnum.Type.COPY.value;
			Integer stateRead = MailReceiverEnum.StateRead.NOT.value;
			MailReceiver mailReceiver = MailReceiver.mailReceiver(mainId, userId, type, stateRead, 1);
			mailReceiverMapper.insert(mailReceiver);
		}
		
		// 删除草稿
		MailDraft mailDraft = new MailDraft().setId(draftId).queryFirst();
		mailDraft.setStatus(0);
		mailDraftMapper.update(mailDraft);
		return R.ok();
	}

	@Override
	public R delete(Long id, String type) {
		if (id == null) {
			return R.error("ID不能为空");
		}
		
		if (!MailEnum.Type.checkIn(type)) {
			return R.error("类型不在范围内");
		}
		
		if (type.equals(MailEnum.Type.DRAFT.value)) {
			mailDraftMapper.deleteTrue(id);
		} else if (type.equals(MailEnum.Type.INBOX.value)) {
			String loginUserId = ShiroUtils.getUserId();
			mailMapper.deleteFalseOfMailReceiverByUk(id, loginUserId);
		} else if (type.equals(MailEnum.Type.DUSTBIN.value)) {
			String loginUserId = ShiroUtils.getUserId();
			
			// 备份数据到已删除
			MailReceiver mailReceiver = new MailReceiver().setUserId(loginUserId).setMainId(id).queryFirst();
			
			Long mainId = id;
			String userId = loginUserId;
			Integer type2 = mailReceiver.getType();
			Integer stateRead = mailReceiver.getStateRead();
			MailReceiverDeleted mailReceiverDeleted = MailReceiverDeleted.mailReceiverDeleted(mainId, userId, type2, stateRead, 1);
			mailReceiverDeletedMapper.insert(mailReceiverDeleted);
			
			// 彻底删除数据
			mailReceiverMapper.deleteTrue(mailReceiver.getId());
		} else if (type.equals(MailEnum.Type.OUTBOX.value)) {
			mailMapper.deleteFalseOfMailMain(id);
		} else {
			return R.error("类型不在范围内");
		}
		return R.ok();
	}

	@Override
	public R readBatchFromInbox(String ids) {
		mailMapper.readBatchOfMailReceiver(ids);
		return R.ok();
	}

	@Override
	public R deleteBatchFromInbox(String ids) {
		mailMapper.deleteFalseBatchOfMailReceiver(ids);
		return R.ok();
	}

	@Override
	public R deleteBatchFromDraft(String ids) {
		mailMapper.deleteFalseBatchOfMailDraft(ids);
		return R.ok();
	}

	@Override
	public R deleteBatchFromOutbox(String ids) {
		mailMapper.deleteFalseBatchOfMailMain(ids);
		return R.ok();
	}

	@Override
	public R rebackBatchFromDustbin(String ids) {
		mailMapper.rebackBatchFromDustbin(ids);
		return R.ok();
	}

	@Override
	public R detail(Long id, String type) {
		if (id == null) {
			return R.error("ID不能为空");
		}
		
		if (!MailEnum.Type.checkIn(type)) {
			return R.error("类型不在范围内");
		}
		
		if (type.equals(MailEnum.Type.DRAFT.value)) {
			MailDraft entity = new MailDraft().setId(id).queryFirst();
			TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
			
			String title = entity.getTitle();
			String extraFile = entity.getExtraFile();
			String senderUserId = tsUserChange.getUserId();
			String senderUserName = tsUserChange.getUserName();
			String createTime = DateUtil.getYYYY_MM_DD_HH_mm_ss(entity.getCreateTime());
			String receivers = entity.getReceiverArr();
			String content = entity.getDetail();
			GetContentDto dto = new GetContentDto(id, type, title, extraFile, senderUserId, senderUserName, createTime, receivers, content);
			return R.ok(dto);
		} else if (type.equals(MailEnum.Type.INBOX.value)
				|| type.equals(MailEnum.Type.OUTBOX.value)
				|| type.equals(MailEnum.Type.DUSTBIN.value)) {
			
			MailMain entity = new MailMain().setId(id).queryFirst();
			TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
			
			String title = entity.getTitle();
			String extraFile = entity.getExtraFile();
			String senderUserId = tsUserChange.getUserId();
			String senderUserName = tsUserChange.getUserName();
			String createTime = DateUtil.getYYYY_MM_DD_HH_mm_ss(entity.getCreateTime());
			String receivers = entity.getReceivers();
			String content = entity.getDetail();
			GetContentDto dto = new GetContentDto(id, type, title, extraFile, senderUserId, senderUserName, createTime, receivers, content);
			return R.ok(dto);
		} else {
			return R.error("类型不在范围内");
		}
	}
}
